#pragma once

#include"Common.h"

#include"BuildTask.h"
#include"MacroSearcher.h"

class ProductionManager
{
public:
	void OnFrame()
	{
		vector<int> toRemove;
		for(int taskIndex = 0 ; taskIndex < _tasks.size() ; ++taskIndex)
		{
			BuildTask& whichTask = _tasks[taskIndex];
			if(whichTask.Type == BuildTask::Build)
			{
				if(whichTask.State == BuildTask::WaitForCanMake)
				{
					if(!whichTask.WhereToBuild.isValid())
					{
						whichTask.WhereToBuild = BH.GetABuildTile(whichTask.WhatToBuild , whichTask.BaseIndex);
					}
					if(whichTask.Worker == NULL)
					{
						whichTask.Worker = GetANearWorker(whichTask.WhereToBuild);
						Build(whichTask.Worker , whichTask.WhatToBuild , whichTask.WhereToBuild);
						whichTask.State = BuildTask::Asigned;
					}
					break;
				}
				else if(whichTask.State == BuildTask::Asigned)
				{
					if(whichTask.Worker->getHitPoints() <= 0)
					{
						whichTask.State = BuildTask::WaitForCanMake;
					}
					else if(whichTask.Worker->getType() == whichTask.WhatToBuild)
					{
						toRemove.push_back(taskIndex);
						whichTask.State = BuildTask::Morphing;
					}
					break;
				}
				else if(whichTask.State == BuildTask::Morphing)
				{

				}
			}
			else if(whichTask.Type == BuildTask::CreateUnit)
			{
				for each(Unit* whichUnit in Broodwar->self()->getUnits())
				{
					if(whichUnit->getType() == UnitTypes::Zerg_Larva)
					{
						if(Broodwar->canMake(whichUnit , whichTask.WhatToBuild))
						{
							whichUnit->morph(whichTask.WhatToBuild);
							toRemove.push_back(taskIndex);
							whichTask.State = BuildTask::Morphing;
							break;
						}
					}
				}
				break;
			}
		}
		for each(int i in toRemove)
		{
			_tasks.erase(_tasks.begin() + i);
		}
	}
	void AddTasks(const vector<BuildTask>& tasks)
	{
		for(int taskIndex = 0 ; taskIndex < tasks.size() ; ++taskIndex)
		{
			_tasks.push_back(tasks[taskIndex]);
		}
	}
	void Search()
	{
		Broodwar->printf("I wiil search.");
		Macro::MacroSearcher searcher;
		searcher.AlphaBeta(1000);
	}
private:
	vector<BuildTask> _tasks;
};